﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.RoleMenuCommand;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.RoleMenuCommandHandler
{
    /// <summary>
    /// 添加角色菜单表
    /// </summary>
    public class AddRoleMenuCommandHandler : IRequestHandler<AddRoleMenuCommand, APIResult<string>>
    {
        private readonly IBaseRepository<RoleMenuModel> rolemenuRepos;

        public AddRoleMenuCommandHandler(IBaseRepository<RoleMenuModel> rolemenuRepos)
        {
            this.rolemenuRepos = rolemenuRepos;
        }

        /// <summary>
        /// 添加角色菜单表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<string>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();
            //1.通过RoleId 角色ID查询所有数据批量删除
            var list = rolemenuRepos.GetAll().Result.Where(x=>x.RoleId == request.RoleId).ToList();
            await rolemenuRepos.DeleteRemove(list);

            //2.通过list<>MenuId 批量添加
            var obj = request.MenuId.Select(x=> new RoleMenuModel { MenuId = x , RoleId = request.RoleId}).ToList();
            var res = rolemenuRepos.AddRanges(obj).Result;
            result.Code = APIEnum.添加成功;
            result.Msg = APIEnum.添加成功.ToString();
            result.data = res.ToString();
            return await Task.FromResult(result);
        }
    }
}
